package com.qiuxi.modules.system.domain.department;

import com.cartisan.CartisanContext;
import com.cartisan.domains.AbstractEntity;
import com.cartisan.domains.AggregateRoot;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * @author colin
 */
@Entity
@Table(name = "sys_departments")
@Getter
@EqualsAndHashCode(callSuper = true)
public class Department  extends AbstractEntity implements AggregateRoot {
    @Id
    @Column(name = "id")
    private Long id;

    @Column(name = "name")
    private String name;
    @Column(name = "parent_id")
    private Long parentId;
    @Column(name = "type")
    private Integer type;
    @Column(name = "code")
    private String code;

    @Column(name = "description")
    private String description;
    @Column(name = "sort")
    private Integer sort;

    @Column(name = "enabled")
    private boolean enabled;


    private Department() {

    }

    public Department(Long id, Long parentId, String name, Integer type,Integer sort) {
        DepartmentTypeValidator validator = CartisanContext.getBean(DepartmentTypeValidator.class);
        if (!validator.isValid(parentId, type)){
            throw new RuntimeException();
        }

        DepartmentCodeGenerator generator = CartisanContext.getBean(DepartmentCodeGenerator.class);

        this.id = id;
        this.parentId = parentId;
        this.name = name;
        this.type = type;
        this.code = generator.generate(parentId, type);

        this.description = "";
        this.sort = sort;

        this.enabled=true;
    }

    public void change(Long parentId, String name, Integer type){
        DepartmentTypeValidator validator = CartisanContext.getBean(DepartmentTypeValidator.class);
        if (!validator.isValid(parentId, type)){
            throw new RuntimeException();
        }

        DepartmentCodeGenerator generator = CartisanContext.getBean(DepartmentCodeGenerator.class);

        this.parentId = parentId;
        this.name = name;
        this.type = type;
        this.code = generator.generate(parentId, type);
    }

    public void changeDescriptionInfo(String description, int sort){
        this.description = description;
        this.sort = sort;
    }

    public void enable(){
        this.enabled = true;
    }

    public void disable() {
        this.enabled = false;
    }
}
